<?php

/*
	Class: Blog_Admin

	About: Author
		Jaybill McCarthy and Rich Joslin

	About: License
		<http://communit.as/docs/license>

	About: See Also
		<Cts_Controller_Action_Abstract>
		<Cts_Controller_Action_Admin>
*/
class Blog_AdminController extends  Cts_Controller_Action_Admin {

	/* Group: Instance Methods */

	/*
		Function: init
			Invoked automatically when an instance is created.
			For this class, does nothing other than initialize the parent object (calls init() on the parent instance).
	*/
	function init() {
		parent::init();
	}

	/* Group: Actions */

	/*
		Function: index		
	*/
	function indexAction() {
		$request = new Cts_Request($this->getRequest());
		$users_table = new Users();
		$posts_table = new BlogPosts();
		$cats_table = new BlogCategories();
		$comments_table = new BlogComments();
		$posts_cats_table = new BlogPostsCategories();

		$url = "/".$this->_request->getModuleName()."/".$this->_request->getControllerName()."/".$this->_request->getActionName();
		$status_filter_url = $url;

		$status_filter = null;
		$searchterm = null;
		$month_filter = null;
		$cat_filter = null;

		// REBUILD URLS WITH PROPER PARAMS

		$sortables = array(
			urlencode('title asc')  => 'Title - Asc',
			urlencode('title desc') => 'Title - Desc',
			urlencode('author_username asc') => 'Author Username - Asc',
			urlencode('author_username desc') => 'Author Username - Desc',
			urlencode('created_on asc') => 'Created On - Asc',
			urlencode('created_on desc') => 'Created On - Desc',
			urlencode('publish_on asc') => 'Publish On - Asc',
			urlencode('publish_on desc') => 'Publish On - Desc',
			urlencode('updated_on asc') => 'Updated On - Asc',
			urlencode('updated_on desc') => 'Updated On - Desc'
			);
			
		$this->view->sortables = $sortables;
		
		if ($request->has('sort') && $request->sort != "") {
			$sort = urldecode($request->sort);
			$url .= "/sort/".urlencode($sort);
			$status_filter_url .= "/sort/".urlencode($sort);
			$this->view->sort = urlencode($request->sort);
		} else {
			$sort = 'created_on desc';
			$this->view->sort = urlencode($sort);
		}
		if ($request->has('searchterm') && $request->searchterm != "") {
			$searchterm = $request->searchterm;
			$url .= "/searchterm/".urlencode($searchterm);
			$status_filter_url .= "/searchterm/".urlencode($searchterm);
			$this->view->searchterm = $searchterm;
		}
		if ($request->has('status_filter') && $request->status_filter != "") {
			$status_filter = $request->status_filter;
			$url .= "/status_filter/".$status_filter;
			$this->view->status_filter = $status_filter;
		}
		if ($request->has('month_filter') && $request->month_filter != "") {
			$month_filter = $request->month_filter;
			$url .= "/month_filter/".$month_filter;
			$status_filter_url .= "/month_filter/".$month_filter;
			$this->view->month_filter = $month_filter;
		}
		if ($request->has('cat_filter') && $request->cat_filter != "") {
			$cat_filter = $request->cat_filter;
			$url .= "/cat_filter/".$cat_filter;
			$status_filter_url .= "/cat_filter/".$cat_filter;
			$this->view->cat_filter = $cat_filter;
		}

		// now that all the params are in the URL, turn this post into a get
		if ($this->_request->isPost()) {
			$this->_redirect($url);
		}

		$this->view->status_filter_url = $status_filter_url;

		$whereclause = null;

		// GET STATUS FILTER COUNTS

		$post_counts = array();
		$post_counts['all'] = $posts_table->getCountByWhereClause(null);
		$post_counts['published'] = $posts_table->getCountByWhereClause("active = 1");
		// TODO - determine what criteria makes a post a draft or a review
		$post_counts['review'] = $posts_table->getCountByWhereClause("active = 0");
		$post_counts['draft'] = $posts_table->getCountByWhereClause("active = 0");

			

		if (!is_null($searchterm) || !is_null($status_filter) || !is_null($month_filter) || !is_null($cat_filter)) {

			$select = Zend_DB_Table::getDefaultAdapter()->select();

			if (!is_null($searchterm)) {
				$keyword_where = Zend_DB_Table::getDefaultAdapter()->quoteInto("title like ?", "%".$searchterm."%")
					.Zend_DB_Table::getDefaultAdapter()->quoteInto(" or body like ?", "%".$searchterm."%")
					.Zend_DB_Table::getDefaultAdapter()->quoteInto(" or tags like ?", "%".$searchterm."%")
					.Zend_DB_Table::getDefaultAdapter()->quoteInto(" or slug like ?", "%".$searchterm."%");
				$select->where($keyword_where);
			}

			if (!is_null($cat_filter)) {
				$joins = $posts_cats_table->fetchAllArray($posts_cats_table->select()->where("category_id = ?", $cat_filter));

				$cat_posts = "";
				$cnt = 0;
				foreach ($joins as $join) {
					$cat_posts .= $join['post_id'];
					if(++$cnt != count($joins)) {$cat_posts.=",";}
				}
				
				$select->where("id in (" . $cat_posts .")");
			}

			if (!is_null($month_filter)) {
				$start_date = $this->firstOfMonth(str_replace("-", " ", $month_filter));
				$end_date = $this->firstOfNextMonth(str_replace("-", " ", $month_filter));
				$select->where("created_on between '".$start_date."' and '".$end_date."'");
			}

			$all_select = clone $select;
			$all_where = implode(" ", $all_select->getPart('where'));
			if ($all_where == "") {
				$all_where = null;
			}
			$post_counts['all'] = $posts_table->getCountByWhereClause($all_where);

			$published_select = clone $select;
			$published_select->where("active = 1");
			$published_where = implode(" ", $published_select->getPart('where'));
			if ($published_where == "") {
				$published_where = null;
			}
			$post_counts['published'] = $posts_table->getCountByWhereClause($published_where);

			// TODO - determine what criteria makes a post a draft or a review

			$review_select = clone $select;
			$review_select->where("active = 0");
			$review_where = implode(" ", $review_select->getPart('where'));
			if ($review_where == "") {
				$review_where = null;
			}
			$post_counts['review'] = $posts_table->getCountByWhereClause($review_where);

			$draft_select = clone $select;
			$draft_select->where("active = 0");
			$draft_where = implode(" ", $draft_select->getPart('where'));
			if ($draft_where == "") {
				$draft_where = null;
			}
			$post_counts['draft'] = $posts_table->getCountByWhereClause($draft_where);

			if (!is_null($status_filter)) {
				switch ($status_filter) {
					case 'published':
						$select->where('active = 1');
						break;
					case 'review':
						$select->where('active = 0');
						break;
					case 'draft':
						$select->where('active = 0');
						break;
					default:
						break;
				}
			}

			$whereclause = implode(" ", $select->getPart('where'));
		}

		$this->view->post_counts = $post_counts;

		$per_page = Cts_Registry::get('admin_posts_per_page', 'blog');
		$page = $this->_request->getParam('page', 0);
		$total = $posts_table->getCountByWhereClause($whereclause);

		$this->makePager($page, $per_page, $total, $url);
		
		
		$tmp_posts = $posts_table->fetchAll($whereclause, $sort, $per_page, $per_page * $page);
		$tmp_posts = $tmp_posts->toArray();
		$posts = array();
		foreach ($tmp_posts as $post) {

			// POST COMMENTS
			$where = $comments_table->getAdapter()->quoteInto("post_id = ?", $post['id']);
			$tmp_comments = $comments_table->fetchAllArray($where);
			$post['comment_count'] = count($tmp_comments);
			$where = $comments_table->getAdapter()->quoteInto("post_id = ? and active = 0", $post['id']);
			$tmp_comments = $comments_table->fetchAllArray($where);
			$post['has_inactive_comments'] = count($tmp_comments);

			// POST CATEGORIES
			$joins = $posts_cats_table->fetchAllArray($posts_cats_table->select()->where("post_id = ?", $post['id']));
			// dd($joins);
			$cats = array();
			foreach ($joins as $join) {
				$cats[] = $cats_table->findArray($join['category_id']);
			}
			$post['cats'] = $cats;

			// POST AUTHOR
			$post['author_user'] = $users_table->findArray($post['author_username']);

			// POST STATUS
			if ($post['active'] == 1) {
				$post['status'] = "Published";
			} else {
				$post['status'] = "Draft";
			}

			$posts[] = $post;
		}

		$params = array('posts' => $posts);
		$params = $this->_cts_plugin->doFilter($this->_mca . "_post_select", $params); // FILTER HOOK
		$posts = $params['posts'];

		if (count($posts) > 0) {
			$this->view->posts = $posts;
		}

		// TODO - determine permissions - can user see the review filter link ?
		$this->view->show_review_filter = true;

		// DATE FILTER OPTIONS
		if($posts_table->getCountByWhereClause() > 0){
			$latest_date = new Zend_Date(strtotime($posts_table->getLatestCreateDate()));
			$earliest_date = new Zend_Date(strtotime($posts_table->getEarliestCreateDate()));
		
			$loop_date = clone $latest_date;
			$loop_date->addMonth(1);
			$filter_dates = array();
			$filter_dates[''] = "Show all dates";
			while ($earliest_date->compare($loop_date) < 1) {
				$loop_date->addMonth(-1);
				// while the earliest date is earlier than the loop date
				// until the loop date is earlier than the earliest date
				if ($posts_table->timeFrameHasPosts($this->firstOfMonth($loop_date), $this->firstOfNextMonth($loop_date))) {
					// only add the month and year to the list if there are blog posts in that timeframe
					$monthyear = date("F", strtotime($loop_date))." ".date("Y", strtotime($loop_date));
					$filter_dates[str_replace(" ", "-", $monthyear)] = $monthyear;
				}
			}
			$this->view->filter_dates = $filter_dates;
		}

		// CATEGORY FILTER OPTIONS
		$filter_categories = array();
		$cats = $cats_table->fetchAllArray();
		$filter_cats[''] = "View all Categories";
		foreach ($cats as $cat) {
			if ($cats_table->hasPosts($cat['id'])) {
				$filter_cats[$cat['id']] = $cat['description'];
			}
		}
		$this->view->filter_cats = $filter_cats;
	}
	
	function editAction() {
		$request = new Cts_Request($this->getRequest());
		$errors = array();
		$posts_table = new BlogPosts();
		$media_table = new BlogMedia();
		$modules_table = new Modules();
		$categories_table = new BlogCategories();
		$posts_categories_table = new BlogPostsCategories();
		$categories_tags_table = new BlogCategoriesTags();
		$users_table = new Users();
		$locales_table = new Locales();
		$useWorkflow = $modules_table->isEnabled("workflow");
		
		
		
		$id = null;
		$post = null;
		$pubdate = null;
	   	if($request->has('id')) {
	   		$post = $posts_table->fetchRow($posts_table->select()->where('id = ?',$request->id));	   		
	   		$id = $request->id;
			$media_url = "/uploads/blog/post-".$post->id."/";
			$this->view->media_url = $media_url;
			$media_path = Zend_Registry::get('basepath').$media_url;
	   	}
	   	// check if we're posting
	   	if ($this->getRequest()->isPost()) {
	   		
	   		// media aspect ratio
	   		
	   		$aspect_ratios = $request->getStartsWith("aspect_ratio_media_id");   		
	   		if(count($aspect_ratios) > 0){
	   			foreach($aspect_ratios as $media_ar_field){	   				
	   				$tmp_media_id = substr($media_ar_field,strlen("aspect_ratio_media_id_"),strlen($media_ar_field));
	   				$media_table->update(array("aspect_ratio" => $request->$media_ar_field),"id = ".$tmp_media_id);
	   			}
	   			
	   		}  		
	   		
			$request->addValidator("title", $this->_T("Title is required."));
			
			if (!$request->isValid()) {
				$errors = array_merge($errors, $request->getValidationErrors());
			}

			if($request->has("pubdate_Hour")) {
				$pubdate = mktime(
					$request->pubdate_Hour,
					$request->pubdate_Minute,
					$request->pubdate_Second,
					$request->pubdate_Month,
					$request->pubdate_Day,
					$request->pubdate_Year
				);
				
				if($pubdate === false) {
					$errors[] = $this->_T("Chosen publish date is not valid.");
				}
			}

			if(!$users_table->userExists($request->author_username)){
				$errors[] = $this->_T("Author username is not valid.");
			}

			$raw_metadata_fields = $request->getStartsWith("metadata_");
			
			if(count($raw_metadata_fields) > 0){
				$metadata_fields = array();				
				foreach($raw_metadata_fields as $metadata_field){
					$metadata_fields[substr($metadata_field,strlen("metadata_"))] = $request->$metadata_field;
				}
			}
			
			$params = array(
						"errors" 	=> $errors,
						"request" 	=> $this->getRequest(),
						"username"	=> $this->_identity->username,						);
			$params = Cts_Plugin::doFilter($this->_mca."_pre_save",$params);
			$errors = $params['errors'];			

			if (count($errors) == 0) {

				if (!is_null($post) && array_key_exists('media_staging_file', $_FILES)) {
					if ($_FILES['media_staging_file']['tmp_name'] != '') {
						$destination_filename = $_FILES['media_staging_file']['name'];
						if (!is_dir($media_path)) {
						  	mkdir($media_path, 0777, true);
							Cts_Log::report("Creating blog media folder at ".$media_path, null, Zend_Log::DEBUG);
						}
						if (file_exists($media_path.$destination_filename)) {
							$counter = 1;
							$original_filename = $destination_filename;
							while(file_exists($media_path.$destination_filename)) {
								$destination_filename = $original_filename . "-" . (string)$counter;
								$counter++;
							}
							Cts_Log::report("Renaming a blog media file ".$media_path.$destination_filename." because it already existed.", null, Zend_Log::DEBUG);
						} else {
							Cts_Log::report("Blog media file ".$media_path.$destination_filename." did not exist.", null, Zend_Log::DEBUG);
						}
						Cts_Log::report("Filtering a blog media filename: ".$media_path.$destination_filename, null, Zend_Log::DEBUG);
						$file_filter = new Cts_FilterFilename();
						$destination_filename = $file_filter->filter($destination_filename);
						Cts_Log::report("Filtered a blog media filename: ".$media_path.$destination_filename, null, Zend_Log::DEBUG);
						move_uploaded_file($_FILES['media_staging_file']['tmp_name'], $media_path.$destination_filename);
						// TODO - clear cache ?
						// $cache_path = Cts_Filesystem::getPath('usercache', $username);
						// if (file_exists($cache_path)) {
						// 	Cts_Filesystem::SureRemoveDir($cache_path, false);
						// }
						Cts_Log::report("Blog media file ".$destination_filename." uploaded to ".$media_path, null, Zend_Log::DEBUG);
						if(function_exists("finfo_open")){
							$finfo = finfo_open(FILEINFO_MIME); // return mime type ala mimetype extension						
    						$mime_type = finfo_file($finfo, $media_path.$destination_filename);						
							finfo_close($finfo);
						} else {
							$mime_type = exec("/usr/bin/file -i -b ".$media_path.$destination_filename);
						}
						
						
						$data = array(
							'post_id' => $post->id,
							'filename' => $destination_filename,
							'mime_type' => $mime_type,
							'is_finalized' => '0',
							'sort_order' => '9999',
							'created_on' => date(DB_DATETIME_FORMAT),
							'last_updated_on' => date(DB_DATETIME_FORMAT),
						);
						$media_table->insert($data);
						$where = $media_table->getAdapter()->quoteInto("post_id = ?", $post->id);
						Cts_Sort::reNumber("BlogMedia", $where);
					}
				}

				if (!is_null($post) && array_key_exists('media_final_file', $_FILES)) {
					if ($_FILES['media_final_file']['tmp_name'] != '') {
						$destination_filename = $_FILES['media_final_file']['name'];
						if (!is_dir($media_path)) {
						  	mkdir($media_path, 0777, true);
							Cts_Log::report("Creating blog media folder at ".$media_path, null, Zend_Log::DEBUG);
						}
						if (file_exists($media_path.$destination_filename)) {
							$counter = 1;
							$original_filename = $destination_filename;
							while(file_exists($media_path.$destination_filename)) {
								$destination_filename = $original_filename . "-" . (string)$counter;
								$counter++;
							}
							Cts_Log::report("Renaming a blog media file ".$media_path.$destination_filename." because it already existed.", null, Zend_Log::DEBUG);
						} else {
							Cts_Log::report("Blog media file ".$media_path.$destination_filename." did not exist.", null, Zend_Log::DEBUG);
						}
						Cts_Log::report("Filtering a blog media filename: ".$media_path.$destination_filename, null, Zend_Log::DEBUG);
						$file_filter = new Cts_FilterFilename();
						$destination_filename = $file_filter->filter($destination_filename);
						Cts_Log::report("Filtered a blog media filename: ".$media_path.$destination_filename, null, Zend_Log::DEBUG);
						move_uploaded_file($_FILES['media_final_file']['tmp_name'], $media_path.$destination_filename);
						// TODO - clear cache ?
						// $cache_path = Cts_Filesystem::getPath('usercache', $username);
						// if (file_exists($cache_path)) {
						// 	Cts_Filesystem::SureRemoveDir($cache_path, false);
						// }
						Cts_Log::report("Blog media file ".$destination_filename." uploaded to ".$media_path, null, Zend_Log::DEBUG);
						
						if(function_exists("finfo_open")){
							$finfo = finfo_open(FILEINFO_MIME); // return mime type ala mimetype extension						
    						$mime_type = finfo_file($finfo, $media_path.$destination_filename);						
							finfo_close($finfo);
						} else {
							$mime_type = exec("/usr/bin/file -i -b ".$media_path.$destination_filename);
						}
						
						
						
						$data = array(
							'post_id' => $post->id,
							'filename' => $destination_filename,
							'mime_type' => $mime_type,
							'is_finalized' => '1',
							'sort_order' => '9999',
							'created_on' => date(DB_DATETIME_FORMAT),
							'last_updated_on' => date(DB_DATETIME_FORMAT),
						);
						$media_table->insert($data);
						$where = $media_table->getAdapter()->quoteInto("post_id = ?", $post->id);
						Cts_Sort::reNumber("BlogMedia", $where);
					}
				}

			}

			if (count($errors) == 0) {

				// insert into db
				$data = array(
					"locale" 				=> $this->locale_code,
					"title" 				=> $request->title,										
					"author_username" 		=> $request->author_username,
					"updated_by_username" 	=> $this->_identity->username,
					"updated_on"			=> date(DB_DATETIME_FORMAT),					
					"body"					=> $request->body,
				);

				if ($request->has('post_thumbnail')) {
					$data['metadata'] = serialize(array('thumbnail_media_id' => $request->post_thumbnail));
				}

				if ($request->has('final_media_active')) {
					$media_table->deactivateAll($post->id);
					foreach ($request->final_media_active as $media_id) {
						$media_table->activate($media_id);
					}
				}

				if($request->has('tags')) {
					$data['tags'] = serialize(Cts_Common::makeTagArray($request->tags));
				}

				$data['active'] = $request->checkbox('active');

				if ($pubdate < time()) {
					$pubdate = time();
				}
				
				if (is_null($id)) {
					
					$data['created_on'] = date(DB_DATETIME_FORMAT);
					$data['publish_on'] = date(DB_DATETIME_FORMAT,$pubdate);
					
					// Only create slug on insert
					$fcSlug = new Zend_Filter();
					$fcSlug->addFilter(new Zend_Filter_StringToLower())
						->addFilter(new Zend_Filter_Alnum(true))					
						->addFilter(new Zend_Filter_Word_SeparatorToDash());

					$data['slug'] = $fcSlug->filter($request->title);
					
					if($posts_table->slugExists($data['slug'])) {
						$counter = 1;
						$original_slug = $data['slug'];
						while($posts_table->slugExists($data['slug'])) {
							$data['slug'] = $original_slug . "-" . (string)$counter;
							$counter++;
						}
					}
															
					$id = $posts_table->insert($data);
					
					if(count($metadata_fields) > 0 ){
						foreach($metadata_fields as $key => $value){
							$posts_table->setMetaData($id,$key,$value);
						}							
					}
										
					Cts_Plugin::doAction($this->_mca."_post_insert",
						array(
							"id" 		=> $id,
							"request"	=> $this->getRequest(),							
						)					
					);
					
					$just = "inserted";				
																			
				} else {
					
					$where = $posts_table->getAdapter()->quoteInto("id = ?",$id);
					
					if($post->active == 0) {
						$data['publish_on'] = date(DB_DATETIME_FORMAT,$pubdate);						
					}
					
					$posts_table->update($data,$where);
					
					if(count($metadata_fields) > 0 ){
						foreach($metadata_fields as $key => $value){
							$posts_table->setMetaData($id,$key,$value);
						}							
					}
					
					Cts_Plugin::doAction($this->_mca."_post_update",
						array(
							"id" 		=> $id,
							"request"	=> $this->getRequest(),							
						)					
					);					
					$just = "updated";					
				}
				
				
				if($useWorkflow and $request->has('workflow_status')) {
					$old_status = Workflow_Helper::getCurrentStateId($id,"blog");
					//dd(array($id, "blog", $request->workflow_status, $this->_identity->username));
					if(Workflow_Helper::changeState($id, "blog", $request->workflow_status, $this->_identity->username)) {
						if(Workflow_Helper::stateChangeMakesContentActive("blog", $old_status, $request->workflow_status)) {
							$active_data = array(
								"active" => 1, 
							);
							$posts_table->update($active_data, $posts_table->getAdapter()->quoteInto('id = ?',$id));
						}
					}
				}
				
				$categories_table->clearCategoriesForPost($id);
				if($request->has('category')) {
					$categories = $request->category;
					$categories_tags_table = new BlogCategoriesTags();
					foreach($categories as $category) {
						$categories_table->assignCategoryBySlug($id, $category);
						$category_tags = $categories_tags_table->getTagsByCategoryId($categories_table->getCategoryIdBySlug($category));
						if(count($category_tags) > 0) {
							foreach($category_tags as $category_tag) {
								$posts_table->addTag($id, $category_tag);
							}
						}
					}
				}

				$this->_redirect("/blog/admin/edit/just/".$just."/id/".$id);								
			} else{
				$this->view->errors = $errors;
				$this->view->post = array(
					"title" => $request->title,
					"body" => $request->body,
					"tags" => $request->tags,
					"author_username" => $request->author_username,
					"publish_on" => $pubdate,
				);								
				if($request->has('status')) {
					$this->view->status = $request->status;
				}					
			}
	   	}

		if(!is_null($post)) {
			$post = $post->toArray();
			$post['body'] = stripslashes($post['body']);
			$post['title'] = stripslashes($post['title']);

			if (!is_null($post['id']) && $post['id'] > 0) {

				// STAGING MEDIA FILES
				$where = $media_table->getAdapter()->quoteInto("post_id = ? and is_finalized = 0", $post['id']);
				
								
				$this->view->media_staging = $media_table->fetchAllArray($where, "sort_order asc");				
				$this->view->show_media_staging = true;

				$roles_table = new Roles();
				$my_roles = $roles_table->getRoleShortnamesByUsername($this->_identity->username);
				
				
				if (Cts_ExtraResourceCheck::isAllowed("can_finalize_media","blog",$this->_identity->username)) {
					// FINALIZED MEDIA FILES
					// only for those in the admin role
					$where = $media_table->getAdapter()->quoteInto("post_id = ? and is_finalized = 1", $post['id']);
					$this->view->media_final = $media_table->fetchAllArray($where, "sort_order asc");
					$this->view->show_media_final = true;
				} else {
					$this->view->show_media_final = false;
				}

			}

			// TAGS
			$category_ids = $categories_table->getCategoryIdsByPostId($id);
			$tmp_tags = unserialize($post['tags']);		
			$excluded_tags = array();
			if(count($category_ids) > 0) {
				foreach($category_ids as $category_id) {
					$excluded_tags = array_merge($excluded_tags,$categories_tags_table->getTagsByCategoryId($category_id));
				}
			}
			$post_tags = array();
			foreach($tmp_tags as $tmp_tag) {
				if(!in_array($tmp_tag,$excluded_tags)) {
					$post_tags[] = $tmp_tag;
				}
			}
			$post['tags'] = Cts_Common::makeTagString($post_tags);
			$post['metadata'] = unserialize($post['metadata']);
			$this->view->post = $post;
		}
	   	
		
		$params = array();		
		$params['username'] = $this->_identity->username;
				
		if(!is_null($post)) {			
			$params['id'] = $post['id'];
			
		}
		$params['workflow_options']	= array();
		
		
		if($useWorkflow) {
			if(!is_null($id)) {
				$workflow_state_id = Workflow_Helper::getCurrentStateId($id,"blog");			
				$this->view->workflow_state_id = $workflow_state_id;	
			} else {
				$workflow_state_id = "new";
			}
			$params['workflow_options'] = Workflow_Helper::getStateChangesByUsername($this->_identity->username,$workflow_state_id,"blog");	
			$params = Cts_Plugin::getInstance()->doFilter($this->_mca."_workflow_options",$params);	   	
		   	if(count($params['workflow_options']) > 0) {
		   		$this->view->workflow_options = $params['workflow_options'];	   		
		   	} else {
		   		$this->_redirect("/blog/admin");
		   	}
		}	   	
	   	$this->view->categories = $categories_table->getAllCategories($this->locale_code,true);	
	   	
	   	$this->view->locales_for_translation = $locales_table->getLocaleCodesArray(true);
	   		   	
	   	if(!is_null($post)) {
	   		$this->view->selected_categories = $categories_table->getCategorySlugsByPostId($id);
	   	}
	   	
	   	if($request->has('just')) {
	   		if($request->just == "updated") {
	   			$this->view->success = $this->_T("Post updated.");
	   		}
	   		
	   		if($request->just == "inserted") {
	   			$this->view->success = $this->_T("Post saved.");
	   		}
	   		
	   	}	   	
	}
	
	function translateAction(){
		$request = new Cts_Request($this->getRequest());
		$posts_table = new BlogPosts();
		$id = null;
		$post = null;
		$original_post = null;
		$locales_table = new Locales();	
		
		if($request->has('id')) {
			$id = $request->id;
			$post = $posts_table->fetchRow($posts_table->select()->where("id = ?",$id));
			if(is_null($post)){
				$this->_redirect("/blog/admin/index");
			}
			
			$original_post_id = $posts_table->getMetaData($post->id,"original_post_id");
			
			$original_post = $posts_table->fetchRow($posts_table->select()->where("id = ?",$original_post_id));
			
			if(is_null($original_post)){
				$this->_redirect("/blog/admin/index");
			}
						
		} else {
			$this->_redirect("/blog/admin/index");
		}
		
		if($this->getRequest()->isPost()){
			$errors = array();

			$request->addValidator("title", $this->_T("Title is required."));
			
			if (!$request->isValid()) {
				$errors = array_merge($errors, $request->getValidationErrors());
			}
			
			$post->title = $request->title;
			$post->body = $request->body;		
			
			if(count($errors) == 0){
				$post->save();
				$this->view->success = $this->_T("Translation saved.");
				
				if($request->has('workflow_status')) {
					$old_status = Workflow_Helper::getCurrentStateId($id,"blog");
					
					if(Workflow_Helper::changeState($id, "blog", $request->workflow_status, $this->_identity->username)) {
						if(Workflow_Helper::stateChangeMakesContentActive("blog", $old_status, $request->workflow_status)) {
							$active_data = array(
								"active" => 1, 
							);
							$posts_table->update($active_data, $posts_table->getAdapter()->quoteInto('id = ?',$id));
						}
					}
				}
			} else {
				$this->view->errors = $errors;
			}
		}
		
		$post_array = $posts_table->preparePostForView($post);
		$locale_info = $locales_table->fetchByLocaleCode($post->locale);
		if(!is_null($locale_info)){
			$post_array['locale_info'] = $locale_info->toArray();
		}
		
		$this->view->post = $post_array;		
		$this->view->original_post 	= $posts_table->preparePostForView($original_post);
		
		$workflow_state_id = Workflow_Helper::getCurrentStateId($id,"blog");			
		$this->view->workflow_state_id = $workflow_state_id;		
		$workflow_options = Workflow_Helper::getStateChangesByUsername($this->_identity->username,$workflow_state_id,"blog");
		if(count($workflow_options)){
			$this->view->workflow_options =  $workflow_options;
		} else {
			$this->_redirect(Cts_Registry::get('post_translate_submitted_redirect','blog'));
		}			
	}
	
	function deleteAction() {
		$request = new Cts_Request($this->getRequest());
		$posts_table = new BlogPosts();
		$id = null;
		if($request->has('id')) {
			$id = $request->id;
		} else {
			$this->_redirect("/blog/admin/index");
		}
		if ($this->getRequest()->isPost()) {
			$del = strtolower($request->delete);			
			if ($del == 'yes' && !is_null($id)) {
				$params = array('id' => $id, 'delete_row' => true);
				$params = $this->_cts_plugin->doFilter($this->_mca . "_pre_delete", $params); // FILTER HOOK
				if ($params['delete_row']) {
					$where = $posts_table->getAdapter()->quoteInto('id = ?', $id);
					$posts_table->delete($where);
				}
				$this->_cts_plugin->doAction($this->_mca . "_post_delete", $params); // ACTION HOOK
				$this->view->success = "Post ".$id." has been deleted.";
				$this->view->id = $id;
			} else {
				$this->_redirect('/blog/admin/index');
			}
		} else {
			$this->view->notice = "Warning: You are about to delete post ".$id.". This cannot be undone.";
			if (!is_null($id)) {
				$post = $posts_table->fetchRow($posts_table->select()->where("id = ?",$id));
				if (!is_null($post)) {
					$this->view->post = $post->toArray();
					$this->view->id = $id;
				} else {
					$this->_redirect('/blog/admin/index');
				}
			}
		}
	}

	function deletemediaAction() {
		$request = new Cts_Request($this->getRequest());
		if (!$request->has('id')) {
			$this->_redirect("/default/auth/missing");
		} else {
			$media_table = new BlogMedia();
			$where = $media_table->getAdapter()->quoteInto("id = ?", $request->id);
			$media = $media_table->fetchRowArray($where);
			$this->view->media = $media;
			if ($this->getRequest()->isPost()) {
				$del = strtolower($request->delete);
				if ($del == 'yes' && count($media) >= 1) {
					$media_path = Zend_Registry::get('basepath')."/uploads/blog/post-".$media['post_id']."/".$media['filename'];
					if (file_exists($media_path)) {
						unlink($media_path);
					}
					$media_table->delete($where);
				}
				$this->_redirect("/blog/admin/edit/id/".$media['post_id']);
			}
		}
	}

	function bulkunpublishAction() {
		$request = new Cts_Request($this->getRequest());
		$errors = array();
		if ($request->has('bulk_checkbox')) {
			$post_ids = $request->bulk_checkbox;
			$posts_table = new BlogPosts();
			if ($this->getRequest()->isPost()) {
				if ($posts_table->unpublishBulk($post_ids)) {
					$this->view->success = "Posts unpublished.";
				} else {
					$errors[] = "Unable to unpublish the posts due to a database error.";
				}
			} else {
				$posts = $posts_table->getBulk($post_ids);
				if (count($posts) >= 1) {
					$this->view->posts = $posts;
				} else {
					$errors[] = "No posts found.";
				}
			}
		} else {
			$errors[] = "No posts were selected.";
		}
	}

	function moderateAction() {
		$request = new Cts_Request($this->getRequest());
		if (!$request->has('post_id')) {
			$this->_redirect("/default/auth/missing");
		} else {
			$comments_table = new BlogComments();
			$where = $comments_table->getAdapter()->quoteInto("post_id = ?", $request->post_id);
			$comments = $comments_table->fetchAll($where);
			if(count($comments) > 0) {
				$this->view->comments = $comments_table->prepareRowsetForView($comments);	
			}
		}
	}

	function approvecommentAction() {
		$request = new Cts_Request($this->getRequest());
		if (!$request->has('post_id') || !$request->has('comment_id')) {
			$this->_redirect("/default/auth/missing");
		} else {
			$comments_table = new BlogComments();
			if ($this->_request->isPost()) {
				$data = array(
					'active' => '1',
				);
				$where = $comments_table->getAdapter()->quoteInto("id = ?", $request->comment_id);
				$comments_table->update($data, $where);
				$this->_redirect('/blog/admin/moderate/post_id/'.$request->post_id);
			} else {
				$where = $comments_table->getAdapter()->quoteInto("id = ?", $request->comment_id);
				$this->view->comment = $comments_table->fetchRowArray($where);
			}
		}
	}

	function deletecommentAction() {
		$request = new Cts_Request($this->getRequest());
		if (!$request->has('post_id') || !$request->has('comment_id')) {
			$this->_redirect("/default/auth/missing");
		} else {
			$comments_table = new BlogComments();
			if ($this->_request->isPost()) {
				$where = $comments_table->getAdapter()->quoteInto("id = ?", $request->comment_id);
				$comments_table->delete($where);
				$this->_redirect('/blog/admin/moderate/post_id/'.$request->post_id);
			} else {
				$where = $comments_table->getAdapter()->quoteInto("id = ?", $request->comment_id);
				$this->view->comment = $comments_table->fetchRowArray($where);
			}
		}
	}

	function movemediaupAction() {
		$request = new Cts_Request($this->getRequest());
		$this->moveMedia($request->media_id, $request->post_id, -15);
	}

	function movemediadownAction() {
		$request = new Cts_Request($this->getRequest());
		$this->moveMedia($request->media_id, $request->post_id, 15);
	}

	private function moveMedia($media_id, $post_id, $increment) {
		$class_name = "BlogMedia";
		$row_id = $media_id;
		$parent_id = $post_id;
		$parent_id_column_name = "post_id";
		$redirect = "/blog/admin/edit/id/".$post_id;
		$this->move($class_name, $row_id, $parent_id, $parent_id_column_name, $increment, $redirect);
	}

	private function move($class_name, $row_id, $parent_id, $parent_id_column_name, $increment, $redirect) {
		Cts_Sort::adjustSortValue($class_name, $row_id, $increment);
		Cts_Sort::reNumber($class_name, $parent_id_column_name." = ".$parent_id);
		$this->_redirect($redirect);
	}

	function firstOfMonth($date = null) {
		if (is_null($date)) {
			$date = date("Y-m-d");
		}
		return date("Y-m-01 00:00:00", strtotime($date));
	}

	function firstOfNextMonth($date) {
		if (is_null($date)) {
			$date = date("Y-m-d");
		}
		$month = (int)date("m", strtotime($date));
		$next_month = $month + 1;
		return date("Y-".$next_month."-01 00:00:00", strtotime($date));
	}

}
